package com.ym.medical.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ym.base.enums.FlagEnum;
import com.ym.core.exception.BusinessException;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.medical.dao.PatientFollowupDao;
import com.ym.medical.domain.bo.PublishCouponTarget;
import com.ym.medical.domain.entity.InformationEntity;
import com.ym.medical.domain.entity.PatientDetailEntity;
import com.ym.medical.domain.entity.PatientFollowupEntity;
import com.ym.medical.domain.param.InformationParam;
import com.ym.medical.domain.vo.CouponVo;
import com.ym.medical.domain.vo.FollowupVo;
import com.ym.medical.domain.vo.UserDoctViewVo;
import com.ym.medical.enums.CouponSendWayEnum;
import com.ym.medical.enums.InformationInforStateEnum;
import com.ym.medical.enums.InformationInforTypeEnum;
import com.ym.medical.service.ICouponReceiveRecordSV;
import com.ym.medical.service.ICouponSV;
import com.ym.medical.service.IFollowupSV;
import com.ym.medical.service.IInformationSV;
import com.ym.medical.service.IPatientDetailSV;
import com.ym.medical.service.IUserSV;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: 张文博
 * @version: 2019年09月02日 9:28
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FollowupSVImpl extends BaseSVImpl<PatientFollowupEntity, PatientFollowupDao> implements IFollowupSV {

	@Autowired
	private ICouponReceiveRecordSV iReceiveRecordSV;

	@Autowired
	private IInformationSV informationSV;

	@Autowired
	private IUserSV iUserSV;

	@Autowired
	private IPatientDetailSV iPatientDetailSV;

	@Autowired
	private ICouponSV iCouponSV;

	/**
	 * 随访记录
	 *
	 * @param followupVo
	 * @param currId
	 * @return
	 */
	@Override
	public int saveFollowup(FollowupVo followupVo, Long currId) {

		int rows = 0;
		List<Long> patientIds = followupVo.getPatientIds();
		if (null == patientIds) {
			throw new BusinessException("请选择随访患者");
		}
		String followContent = followupVo.getFollowContent();
		Long couponId = null;
		InformationEntity information = null;
		PatientFollowupEntity followup = null;
		// CouponReceiveRecord receiveRecord = null;
		Long followId = null;
		//List<Long> couponRecordIds = new ArrayList<>();

		//医生信息
		UserDoctViewVo user = iUserSV.selectUserDoctView(currId);
		user.setDate(new Date());
		List<UserDoctViewVo> userInfo = new ArrayList<>();
		List<InformationEntity> informationList = new ArrayList<>();
		UserDoctViewVo newUser = null;
		if (followupVo.getCouponId() != null) {
			couponId = followupVo.getCouponId();

			//患者和用户id list 可变参数传递
			List<PublishCouponTarget> couponTargets = new ArrayList<>();

			for (Long pId : patientIds) {
				//查询userId
				PatientDetailEntity detail = iPatientDetailSV.selectById(pId);
				//放入要发送的人列表 优惠券领取记录
				PublishCouponTarget couponTarget = new PublishCouponTarget();
				couponTarget.setPatientId(pId);
				couponTarget.setUserId(detail.getUserId());
				couponTargets.add(couponTarget);
				//随访记录
				followup = new PatientFollowupEntity();
				followup.setDoctorId(currId);
				followup.setPatientId(pId);
				followup.setFollowContent(followContent);
				followup.setFollowState(FlagEnum.NO.getKey());
				followup.setFollowTime(new Date());
				this.insert(followup);
				followId = followup.getId();
				//消息表
				information = new InformationEntity();
				information.setInforType(InformationInforTypeEnum.FOLLOW_UP.getKey());
				information.setInforState(InformationInforStateEnum.NO_READ.getKey());
				information.setSendTime(new Date());
				information.setSendObjId(currId);
				information.setReceiverObjId(detail.getUserId());
				information.setInforTitle("'" + user.getRealName() + "'");
				information.setInforData(followContent);
				information.setCreateTime(new Date());
				information.setDestination("01");
				user.setFollowId(followId);
				user.setPatientId(pId);
				newUser = new UserDoctViewVo();
				BeanUtils.copyProperties(user, newUser);
				userInfo.add(newUser);
				informationList.add(information);
			}
			List<Long> recordId = iReceiveRecordSV.publishCoupon(
					couponId, CouponSendWayEnum.FOLLOW_UP.getKey(), null,
					currId, user.getRealName(), couponTargets.toArray(new PublishCouponTarget[couponTargets.size()]));
			for (int i = 0; i < userInfo.size(); i++) {
				userInfo.get(i).setCouponIdRecords(recordId);
				String str = JSONObject.toJSONString(userInfo.get(i));
				informationList.get(i).setExtContent(str);
				informationSV.insert(informationList.get(i));
                rows++;
			}

		} else {
			rows = followAndMessage(patientIds, currId, followContent, user);
		}
		return rows;
	}


	/**
	 * 随访和消息记录生成
	 *
	 * @param patientIds
	 * @return
	 */
	private int followAndMessage(List<Long> patientIds, Long currId, String followContent, UserDoctViewVo user) {
		int rows = 0;
		PatientFollowupEntity followup = null;
		InformationEntity information = null;
		Long followId = null;

		for (Long pId : patientIds) {
			//查询userId
			PatientDetailEntity detail = iPatientDetailSV.selectById(pId);
			//随访记录
			followup = new PatientFollowupEntity();
			followup.setDoctorId(currId);
			followup.setPatientId(pId);
			followup.setFollowContent(followContent);
			followup.setFollowState(FlagEnum.NO.getKey());
			followup.setFollowTime(new Date());
			this.insert(followup);
			followId = followup.getId();
			//消息表
			information = new InformationEntity();
			information.setInforType(InformationInforTypeEnum.FOLLOW_UP.getKey());
			information.setInforState(InformationInforStateEnum.NO_READ.getKey());
			information.setSendTime(new Date());
			information.setSendObjId(currId);
			information.setReceiverObjId(detail.getUserId());
			information.setInforTitle("'" + user.getRealName() + "'");
			information.setInforData(followContent);
			information.setCreateTime(new Date());
			information.setDestination("01");
			user.setFollowId(followId);
			user.setPatientId(pId);

			String str = JSONObject.toJSONString(user);
			information.setExtContent(str);
			informationSV.insert(information);
			rows++;

		}
		return rows;
	}


	/**
	 * 随访消息
	 *
	 * @param model
	 * @return
	 */
	@Override
	public List<FollowupVo> followMessage(InformationParam model) {
		String extContent = model.getExtContent();
		JSONObject json = JSONObject.parseObject(extContent);
		String arrs;
		JSONArray couponRecordIds = (JSONArray) json.get("couponIdRecords");
		//String [] couponRecordIds = {"39"};
		Long sendId = model.getSendObjId();
		List<CouponVo> coupons = null;
		int patientId = (int) json.get("patientId");
		//int patientId = 187;
		if (couponRecordIds != null) {
			arrs = StringUtils.join(couponRecordIds, ",");
			coupons = iCouponSV.coupons(arrs, sendId, patientId);
			//根据需要开启
			//coupons = iCouponSV.couponFilter(coupons,false);
		}
		int followId = (int) json.get("followId");
		//int  followId = 25;
		List<FollowupVo> followupVos = mapper.followMessage(followId);
		followupVos.get(0).setCoupons(coupons);
		return followupVos;
	}


}
